import { computed, onMounted, onUnmounted, ref, Ref } from "vue";
type Point = { x: number; y: number } //声明一个类型
interface Options {
    // 取消默认动作
    beforeStart?: (e: TouchEvent) => void
    afterStaret?: (e: TouchEvent) => void
    beforeMove?: (e: TouchEvent) => void
    afterMove?: (e: TouchEvent) => void
    beforeEnd?: (e: TouchEvent) => void
    afterEnd?: (e: TouchEvent) => void

}
export const useSwipe = (element: Ref<HTMLElement | undefined>, options?: Options) => {
    const start = ref<Point>()
    const end = ref<Point>()
    const swiping = ref(false) //是否移动
    const distance = computed(() => { //移动的距离
        if (!start.value || !end.value) { return undefined }
        return {
            x: end.value.x - start.value.x,
            y: end.value.y - start.value.y
        }
    })


    const direction = computed(() => {//移动的方向
        if (!swiping) { return '' }
        if (!distance.value) { return "" } //距离不存在时
        const { x, y } = distance.value
        if (Math.abs(x) > Math.abs(y)) {// 绝对值大时
            return x > 0 ? "right" : "left"
        } else {
            return y > 0 ? "down" : "top"
        }
    })
    const onStart = (e: TouchEvent) => {//当前元素存在时监听
        start.value = {//开始的坐标
            x: e.touches[0].clientX,
            y: e.touches[0].clientY
        }
        end.value = undefined//记录最后的坐标
        swiping.value = true //是否移动
        // options?.afterStaret?.(e)
    }

    onMounted(() => {//默认挂载当前组件
        if (!element.value) { return undefined }
        element.value.addEventListener("touchstart",
            e => {//当前元素存在时监听
                e.preventDefault()
                start.value = {//开始的坐标
                    x: e.touches[0].clientX,
                    y: e.touches[0].clientY
                }
                end.value = undefined//记录最后的坐标
                swiping.value = true //是否移动
            })
        element.value.addEventListener("touchmove", e => {//当前元素存在时监听
            end.value = {//结束的坐标
                x: e.touches[0].clientX,
                y: e.touches[0].clientY
            }
        })
        element.value.addEventListener("touchend", e => {//当前元素存在时监听
            start.value = undefined
            swiping.value = false
            end.value = undefined
        })
    })
    onUnmounted(() => {
        if (!element.value) { return }
        element.value.removeEventListener("touchstart", onStart)
    })//取消监听，防止污染
    return {
        swiping, distance, direction, end, start
    }
}